package pqstorer

//Implements the following interface:
//type ClassStorer interface {
//	Save(Class) error //Update class with id if saved for first time.
//	GetClassByHumanId(int64) (*Class, error)
//	GetClassByYearAndInstitution(int64, string) (*Class, error)
//	GetAllClasses() ([]Class, error)
//}

import (
	"code.google.com/p/jesus-1496/models"
	"code.google.com/p/jesus-1496/utils/db"
)

type ClassStore struct{}

func (p *ClassStore) Save(c *models.Class) error {
	err := db.UnmarshallQuery(&(c.Id), `select upsert_class(
		$1::integer,
		$2::varchar(128),
		$3::varchar(256),
		$4::integer,
		$5::integer);`,
		c.Year,
		c.Institution,
		c.PhotoLocation,
		c.PhotoWidth,
		c.PhotoHeight)
	if err != nil {
		return err
	}

	logger.Printf("Class %+v successfully saved to database.")
	return nil
}

func (p *ClassStore) GetClassByHumanId(humanId int64) (*models.Class, error) {
	var ret models.Class
	err := db.UnmarshallQuery(&ret, `select get_class_by_human_id($1::integer);`,
		humanId)
	if err != nil {
		return nil, err
	}

	return &ret, nil
}

func (p *ClassStore) GetClassByYearAndInstitution(year int64, institution string) (*models.Class, error) {
	var ret models.Class
	err := db.UnmarshallQuery(&ret, `select get_class_by_year_and_institution($1::integer, $2varchar(128));`,
		year, institution)
	if err != nil {
		return nil, err
	}

	return &ret, nil
}

func (p *ClassStore) GetAllClasses() ([]models.Class, error) {
	var ret []models.Class
	err := db.UnmarshallQuery(&ret, `select get_all_classes();`)
	if err != nil {
		return nil, err
	}
	return ret, nil
}
